﻿/// <reference path="../core/jquery-1.4.2.min-vsdoc.js"/>
/// <reference path="../config/sw-config-default.js"/>
/// <reference path="../core/sw-prototype.js"/>
/// <reference path="../core/sw.js"/>
/// <reference path="../core/sw-control-core.js"/>

/***************************************************************************
jQuery Tree
NOTE: Created for SmartUI. 
Copyright 2010, Roy zhang
Features：
1.实现多级Tree功能
2.实现过滤，动态定位
3.模板方法自定义；
4.多选
Update Note：

Needs：
****************************************************************************/

(function ($) {
    ///#region 设置
    var treeSetting = {
        cssfilter: 'tree-filter'
            , cssfiltertxt: 'tree-filter-txt'
            , cssfilterlist: 'tree-filter-list'
            , csscontent: 'tree-content'
            , valuesplit: iconfig.common.valuesplit
            , item: iconfig.tree.teml.item
            , itemmulit: iconfig.tree.teml.itemmulit
    };
    ///#endregion

    $.fn.tree = function (datas, options) {
        /// <summary>pager</summary>
        /// <param name="options" type="Array">配置项</param>
        /// <param name="datas" type="Json">数据源</param>               
        options = $.extend({
            container: iconfig.tree.teml.container
            , item: null
            , showfilter: true
            , ismulit: false
            , fnselected: null
            , expanddept: 0
            , css: 'tree'
        }
        , options);
        var tree = this.addClass(options.css), id = tree.attr('id'), fixheight = 0;
        if (options.showfilter) {//生成tree过滤
            var filter = $('<div/>').addClass(treeSetting.cssfilter);
            var txtfilter = $('<input />').addClass(treeSetting.cssfiltertxt).appendTo(filter);
            var btnfilter = $('<a />').text('Go').appendTo(filter)
            var list = $('<div />').addClass(treeSetting.cssfilterlist).append('<ol />').appendTo(filter);
            filter.prependTo(tree);
            fixheight = filter.getCss('height');
            btnfilter.click(function () {
                treeFilter(id, txtfilter, list);
            });
            txtfilter.keydown(function (e) {
                switch (e.keyCode) {
                    case 38:
                        keySelect(list, $(this), true);
                        break;
                    case 40:
                        if (list.css('display') == 'none')
                            treeFilter(id, txtfilter, list);
                        else
                            keySelect(list, $(this), false, true);
                        break;
                    case 13:
                        if (list.css('display') == 'none')
                            treeFilter(id, txtfilter, list);
                        else
                            if (keySelect(list, $(this), false, false, true))
                                treeFilter(id, txtfilter, list);
                        break;
                }
            });
        }

        var treecontent, nodes; //treecontent:实现tree的内容区域
        if (datas) {
            treecontent = $('<div />').addClass(treeSetting.csscontent)
            .css({ width: tree.css('width'), height: tree.getCss('height') - fixheight }).appendTo(tree);
            bindTree(id, treecontent, datas, options, 0);
        }
        else {
            nodes = tree.children('ul');
            if (nodes.length) {
                nodes.wrap(document.createElement('div'));
                treecontent = nodes.parent().addClass(treeSetting.csscontent)
            }
            else
                treecontent = tree.find('div.' + treeSetting.csscontent);

            if (treecontent.length) {//设置tree的事件
                treecontent.css({ width: tree.css('width'), height: tree.getCss('height') - fixheight });
                buildTree(true, id, treecontent.children('ul').children('li'), options.ismulit, options.fnselected, 0, options.expanddept);
            }
        }
        return tree;
        ///#endregion
    };
    ///#region 公共设置方法
    function bindTree(id, root, datas, options, dept) {
        if (datas.length > 0) {
            var container = $(options.container).appendTo(root);
            if (options.ismulit)
                root.data('count', datas.length); //缓存子选项条数
            var itemtemp = options.item || (options.ismulit ? treeSetting.itemmulit : treeSetting.item);
            ictrcore.teml(container, itemtemp, datas).each(function (i) {
                var data = datas[i], item = $(this);
                if (data && data.rows)
                    bindTree(id, item, data.rows, options, dept + 1);

                buildTree(false, id, item, options.ismulit, options.fnselected, dept, options.expanddept, datas.length == i + 1);
            });
        }
    }

    function buildTree(isbuildchild, treeid, items, ismulit, fnselected, dept, expanddept, isend) {
        var length = items.length;
        if (length) {
            length--;
            items.each(function (i) {
                var item = $(this), node = item.children('a'), child = item.children('ul');
                item.addClass(dept ? ((hasValue(isend) ? isend : length === i) ? 'end' : (child.length ? 'dir' : '')) : 'root');
                if (child.length) {
                    node.addClass('dir').click(function () {//文件夹点击时
                        var node = $(this).toggleClass('opend');
                        node.next('ul').toggle('fast');
                        if (fnselected)
                            fnselected(node, true);
                    });
                    if (ismulit)//多选时，处理checkbox
                        item.children('samp').attr('d', 1).click(function () {
                            dirCheck($(this));
                        });
                    if (isbuildchild) {//当为html格式时处理
                        var childs = child.children('li');
                        item.data('count', childs.length);
                        buildTree(isbuildchild, treeid, childs, ismulit, fnselected, dept + 1, expanddept);
                    }
                    if (dept < expanddept) {//根据设置的深度展开
                        child.show();
                        node.addClass('opend')
                    }
                }
                else {//文件点击时
                    node.click(function () {
                        $('#' + treeid + ' a.selected').removeClass('selected');
                        var node = $(this).addClass('selected');
                        if (fnselected)
                            fnselected(node, false);
                    });
                    if (ismulit)
                        item.children('samp').click(function () {
                            nodeCheck($(this));
                        });
                }
            });
        }
    }
    function keySelect(list, txt, isup, isdown, isenter) {
        var item = list.find("li.selected");
        if (item.length) {
            if (isenter)
                item.click();
            else {
                var select = isdown ? item.next('li') : item.prev('li');
                if (select.length) {
                    select.addClass("selected");
                    item.removeClass("selected");
                }
            }
        }
        else if (isdown) {
            list.find("li:eq(0)").addClass("selected");
        }
        else if (isenter)
            return true;
    }
    function treeFilter(treeid, txt, list) {
        var text = txt.val();
        if (strNotEmpty(text)) {
            if (txt.data('lastValue') !== text) {
                var ol = list.children('ol');
                ol.html('');
                $('#' + treeid + ' ul li a:contains(' + text + ')').each(function () {
                    var item = $(this);
                    $(document.createElement('li')).append(item.text()).appendTo(ol).click(function () {
                        gotoNode(list, txt, item);
                    });
                });
                ictrcore.upselector(txt, list, iconfig.tree.filtercss);
                txt.data('lastValue', text);
            }
            list.show('fast');
        }
    }
    function gotoNode(list, txt, node) {
        node.parents('li').children('a.dir:not(.opend)').each(function () {
            $(this).click();
        });
        node.click();
        list.hide('fast');
        txt.focus();
        //定位选择的项
        setTimeout(function () { ictrcore.gotoNode(node, node.parents('.' + treeSetting.csscontent)); }, 500);
    }
    function dirCheck(dir) {
        var ischeck = !dir.hasClass('selected');
        dir.parent('li').find('ul li samp').attr('class', ischeck ? 'selected' : '');
        dir.removeClass('had');
        nodeCheck(dir);
    }
    function nodeCheck(node) {
        node.toggleClass('selected');
        node.parent().parents('li').each(function () {
            setParent($(this));
        });
    }
    function setParent(node, ischeck) {
        var chk = node.children('samp');
        var checkednum = node.find(' > ul > li samp.selected').length;
        if (checkednum)
            chk.attr('class', checkednum === node.data('count') ? 'selected' : 'had')
        else {
            checkednum = node.find(' > ul > li samp.had').length;
            chk.attr('class', checkednum ? 'had' : '');
        }
        //        setParent(node.parent().parent());
    }
    ///#endregion

    ///#region 公共方法
//    $.fn.treeBindChild = function (options) {
//        
//    }

    $.treeGetValue = function (treeid, chkprop, valuesplit) {
        if (!chkprop)
            chkprop = 'v';

        var sbValues = new StringBuilder();
        $('#' + treeid + ' ul li samp.selected:not([d])').each(function () {
            sbValues.append($(this).attr('v'));
        });
        if (sbValues.isNotEmpty())
            return sbValues.toString(valuesplit || treeSetting.valuesplit);
        return '';
    }
    ///#endregion
})(jQuery);